import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import { View, Text, Button, ScrollView, Image } from '@tarojs/components';
import { Dialog, Cell } from '@antmjs/vantui';
import PdsEmpty from '@/components/common/pds_empty';
import './index.scss'
import { cancelWalletUseAuthorize, dealWalletUseAuthorize, queryWalletUserAuthorize } from '@/services/api/wallet';
import { formatDate } from '@/utils/fomatter';
import { findNameByFieldNameAndDictItemValue } from '@/services/api/common';

class PersonInfoUseRecord extends Component {

  config = {
    navigationBarTitleText: ''
  }

  state = {
    dataList: [],
    refresherTriggered: false,
    skeletonLoading: true,
    showDialog: false,
    refuseItem: {}
  }



  componentWillMount() {
    this.requestListData(false);
  }
  componentDidMount() { }
  componentWillReceiveProps(nextProps, nextContext) { }
  componentWillUnmount() { }

  //自定义下拉刷新被触发
  onRefresherRefresh(e) {
    this.setState({ refresherTriggered: true })
    console.log(e, '自定义下拉刷新被触发')
    this.requestListData(false);
  }

  // 滚动到底部上拉加载
  scrolltoLower() {
    this.requestListData(true);
  }

  /**
   * 快速滑动不触发onScrollToLower 的bug
   * @param param0 
   */
  onScroll = ({ detail: { scrollTop, scrollHeight } }) => {
    const { screenHeight, } = Taro.getSystemInfoSync()
    if (
      scrollTop + screenHeight + 100 >= scrollHeight
    ) {
      // this.scrolltoLower(); // 手动触发 onScrollToLower
    }
  };

  /**
  * 
  * @param isAdd 
  */
  requestListData(isAdd) {
    const { dataList, } = this.state;
    var offset = isAdd ? dataList.length : 0;
    queryWalletUserAuthorize(null,offset).then((resp) => {
      if (resp.code === 200) {
        if (isAdd) {
          var tempList: any[] = dataList
          tempList.push(...resp.data)
          this.setState({ dataList: tempList });
        } else {
          this.setState({ dataList: resp.data });
        }
      }
      this.setState({ refresherTriggered: false, skeletonLoading: false })
    })
  }



  refuse(value) {

    dealWalletUseAuthorize(value['authId'], false).then((resp) => {
      if (resp.code === 200) {
        const { dataList, } = this.state;
        var temp = dataList.filter(item => item != value)
        this.setState({ dataList: temp })
      }
    })

  }



  agree(value) {
    dealWalletUseAuthorize(value['authId'], true).then((resp) => {
      if (resp.code === 200) {
        this.requestListData(0)
      }
    })
  }


  secureDialog(value) {
    this.setState({ refuseItem: value, showDialog: true })
  }

  secure() {
    const { refuseItem } = this.state;
    cancelWalletUseAuthorize(refuseItem['authId']).then((resp) => {
      if (resp.code === 200) {
        const { dataList, } = this.state;
        var temp = dataList.filter(item => item != refuseItem)
        this.setState({ dataList: temp })
      }
    })
  }


  render() {
    const { dataList, refresherTriggered, showDialog } = this.state;
    var scrollTop = 0;
    return (
      <View className='page'>
        <ScrollView
          className='scrollview'
          scrollY
          scrollWithAnimation
          refresherEnabled
          scrollTop={scrollTop}
          refresherTriggered={refresherTriggered}
          lowerThreshold={150}
          onRefresherRefresh={this.onRefresherRefresh.bind(this)} // 使用箭头函数的时候 可以这样写 `onScrollToUpper={this.onScrollToUpper}`
          onScrollToLower={this.scrolltoLower.bind(this)}
          onScroll={this.onScroll.bind(this)}
        >
          {
            dataList.length === 0 ? <PdsEmpty placeholderText='暂无相关数据'></PdsEmpty> : null
          }
          {
            dataList.map((item, index) => {
              return <View className='table-content-item'>
                <View className='table-content-item-top'>
                  <Image src={require('@/assets/icons/public/public_ydt_icon.svg')}></Image>
                  <Text>{item['targetOrgName']}</Text>
                </View>
                <View className='context'>
                  <Cell title={'授权内容'} value={item['digitalType'] === 1 ? "实名信息" : '-'} border={false} />
                  {
                    item['authorizeStatus'] !== 1 ? <>
                      <Cell title={'授权时间'} value={formatDate(item['authorizeTime'], 'YYYY-MM-DD')} border={false} />
                      <Cell title={'过期时间'} value={formatDate(item['expirationTime'], 'YYYY-MM-DD')} border={false} />
                      <Cell title={'链上Hash'} value={item['txHash']} border={false} />
                    </> : null
                  }
                  <Cell title={'授权状态'} value={findNameByFieldNameAndDictItemValue('authorize_status', item['authorizeStatus'])} border={false} />
                </View>
                <View className='bottom-button'>
                  {
                    item['authorizeStatus'] === 1 ? <>
                      <Button className='refuse-button' onClick={(e) => this.refuse(item)}>拒绝</Button>
                      <Button className='agree-button' onClick={(e) => this.agree(item)}>同意授权 </Button>
                    </> : <Button className='secure-button' onClick={(e) => this.secureDialog(item)}>解除授权</Button>
                  }
                </View>
              </View>
            })
          }
        </ScrollView>
        <Dialog
          id="vanDialog3"
          title="确定解除授权？"
          message='解除授权后，机构将不能再读取你保存在道以盾的个人信息'
          confirmButtonText='解除授权'
          cancelButtonText='暂不解除'
          showConfirmButton
          showCancelButton
          show={showDialog}
          onClose={() => this.setState({ showDialog: false, refuseItem: {} })}
          onCancel={() => this.setState({ showDialog: false, refuseItem: {} })}
          onConfirm={() => this.secure()}
        ></Dialog>
      </View>
    );
  }
}
export default PersonInfoUseRecord;